<template>
  <div class="crawler-config">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6" v-for="stat in statistics" :key="stat.title">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon>
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">{{ stat.title }}</div>
              <div class="stat-value">{{ stat.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主配置区域 -->
    <el-card class="config-main">
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="平台配置" description="选择数据源和账号" />
        <el-step title="规则配置" description="设置抓取规则" />
        <el-step title="数据预览" description="验证数据格式" />
        <el-step title="任务配置" description="设置执行计划" />
      </el-steps>

      <!-- 步骤内容区 -->
      <div class="step-content">
        <!-- 第一步：平台配置 -->
        <div v-show="currentStep === 0">
          <el-form :model="platformConfig" label-width="120px">
            <!-- 平台选择 -->
            <el-form-item label="数据源平台">
              <el-select v-model="platformConfig.platform" placeholder="请选择平台" @change="handlePlatformChange">
                <el-option v-for="platform in platformList" :key="platform.value" :label="platform.label"
                  :value="platform.value">
                  <div class="platform-option">
                    <img :src="platform.icon" class="platform-icon" />
                    <span>{{ platform.label }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 账号配置 -->
            <el-form-item label="账号选择">
              <div class="account-config">
                <el-table :data="platformConfig.accounts" @selection-change="handleAccountSelection">
                  <el-table-column type="selection" width="55" />
                  <el-table-column label="账号" prop="name" />
                  <el-table-column label="状态">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                        {{ scope.row.status === 'active' ? '正常' : '异常' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="最后使用时间" prop="lastUsedTime" />
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button type="primary" link @click="testAccount(scope.row)">
                        测试
                      </el-button>
                      <el-button type="danger" link @click="removeAccount(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <div class="account-actions">
                  <el-button type="primary" @click="showAddAccountDialog">
                    添加账号
                  </el-button>
                  <el-button @click="batchTestAccounts">
                    批量测试
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <!-- 代理配置 -->
            <el-form-item label="代理设置">
              <el-radio-group v-model="platformConfig.proxyType">
                <el-radio label="none">不使用代理</el-radio>
                <el-radio label="auto">自动分配</el-radio>
                <el-radio label="manual">手动指定</el-radio>
              </el-radio-group>

              <div v-if="platformConfig.proxyType === 'manual'" class="proxy-list">
                <el-table :data="platformConfig.proxyList">
                  <el-table-column label="代理地址" prop="host" />
                  <el-table-column label="端口" prop="port" width="100" />
                  <el-table-column label="类型" prop="type" width="100" />
                  <el-table-column label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                        {{ scope.row.status === 'active' ? '可用' : '不可用' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button type="primary" link @click="testProxy(scope.row)">
                        测试
                      </el-button>
                      <el-button type="danger" link @click="removeProxy(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <div class="proxy-actions">
                  <el-button type="primary" @click="showAddProxyDialog">
                    添加代理
                  </el-button>
                  <el-button @click="importProxyList">
                    批量导入
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 第二步：规则配置 -->
        <div v-show="currentStep === 1">
          <el-form :model="ruleConfig" label-width="120px">
            <!-- 数据类型 -->
            <el-form-item label="数据类型">
              <el-checkbox-group v-model="ruleConfig.dataTypes">
                <el-checkbox v-for="type in availableDataTypes" :key="type.value" :label="type.value">
                  {{ type.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <!-- 时间范围 -->
            <el-form-item label="时间范围">
              <el-date-picker v-model="ruleConfig.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>

            <!-- 关键词配置 -->
            <el-form-item label="关键词">
              <el-tag v-for="keyword in ruleConfig.keywords" :key="keyword" closable @close="removeKeyword(keyword)">
                {{ keyword }}
              </el-tag>
              <el-input v-if="showKeywordInput" v-model="newKeyword" class="keyword-input" size="small"
                @keyup.enter="addKeyword" @blur="addKeyword" />
              <el-button v-else class="button-new-keyword" size="small" @click="showKeywordInput = true">
                + 添加关键词
              </el-button>
            </el-form-item>

            <!-- 筛选条件 -->
            <el-form-item label="筛选条件">
              <div v-for="(filter, index) in ruleConfig.filters" :key="index" class="filter-item">
                <el-select v-model="filter.field" placeholder="选择字段">
                  <el-option v-for="field in availableFields" :key="field.value" :label="field.label"
                    :value="field.value" />
                </el-select>
                <el-select v-model="filter.operator" placeholder="条件">
                  <el-option label="大于" value=">" />
                  <el-option label="小于" value="<" />
                  <el-option label="等于" value="=" />
                  <el-option label="包含" value="contains" />
                </el-select>
                <el-input v-model="filter.value" placeholder="值" />
                <el-button type="danger" @click="removeFilter(index)">删除</el-button>
              </div>
              <el-button type="primary" @click="addFilter">添加条件</el-button>
            </el-form-item>

            <!-- 高级配置 -->
            <el-form-item label="高级配置">
              <el-collapse>
                <el-collapse-item title="请求配置">
                  <el-form-item label="请求间隔(秒)">
                    <el-input-number v-model="ruleConfig.advanced.requestInterval" :min="1" />
                  </el-form-item>
                  <el-form-item label="超时时间(秒)">
                    <el-input-number v-model="ruleConfig.advanced.timeout" :min="1" />
                  </el-form-item>
                  <el-form-item label="重试次数">
                    <el-input-number v-model="ruleConfig.advanced.retryTimes" :min="0" />
                  </el-form-item>
                </el-collapse-item>
              </el-collapse>
            </el-form-item>
          </el-form>
        </div>

        <!-- 第三步：数据预览 -->
        <div v-show="currentStep === 2">
          <div class="preview-actions">
            <el-button type="primary" @click="fetchPreviewData" :loading="previewLoading">
              获取预览数据
            </el-button>
            <el-button @click="exportPreview">导出预览</el-button>
          </div>

          <el-table v-loading="previewLoading" :data="previewData" border style="width: 100%">
            <el-table-column v-for="col in previewColumns" :key="col.prop" :prop="col.prop" :label="col.label" />
          </el-table>

          <div class="preview-stats">
            <el-alert title="数据预览统计" type="info" :description="previewStats" show-icon />
          </div>
        </div>

        <!-- 第四步：任务配置 -->
        <div v-show="currentStep === 3">
          <el-form :model="taskConfig" label-width="120px">
            <el-form-item label="任务名称">
              <el-input v-model="taskConfig.name" placeholder="请输入任务名称" />
            </el-form-item>

            <el-form-item label="执行方式">
              <el-radio-group v-model="taskConfig.executeType">
                <el-radio label="once">单次执行</el-radio>
                <el-radio label="schedule">定时执行</el-radio>
                <el-radio label="periodic">周期执行</el-radio>
              </el-radio-group>
            </el-form-item>

            <template v-if="taskConfig.executeType === 'schedule'">
              <el-form-item label="执行时间">
                <el-date-picker v-model="taskConfig.scheduleTime" type="datetime" placeholder="选择执行时间" />
              </el-form-item>
            </template>

            <template v-if="taskConfig.executeType === 'periodic'">
              <el-form-item label="执行周期">
                <el-select v-model="taskConfig.period">
                  <el-option label="每小时" value="hourly" />
                  <el-option label="每天" value="daily" />
                  <el-option label="每周" value="weekly" />
                  <el-option label="每月" value="monthly" />
                </el-select>
              </el-form-item>
              <el-form-item label="具体时间">
                <el-time-picker v-model="taskConfig.periodicTime" />
              </el-form-item>
            </template>

            <el-form-item label="数据处理">
              <el-checkbox-group v-model="taskConfig.dataProcessing">
                <el-checkbox label="dedup">数据去重</el-checkbox>
                <el-checkbox label="clean">数据清洗</el-checkbox>
                <el-checkbox label="transform">格式转换</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="存储配置">
              <el-radio-group v-model="taskConfig.storageType">
                <el-radio label="database">数据库</el-radio>
                <el-radio label="file">文件</el-radio>
                <el-radio label="api">API推送</el-radio>
              </el-radio-group>

              <template v-if="taskConfig.storageType === 'file'">
                <el-select v-model="taskConfig.fileFormat">
                  <el-option label="CSV" value="csv" />
                  <el-option label="Excel" value="excel" />
                  <el-option label="JSON" value="json" />
                </el-select>
              </template>
            </el-form-item>
          </el-form>
        </div>

        <!-- 步骤操作按钮 -->
        <div class="step-actions">
          <el-button v-if="currentStep > 0" @click="prevStep">
            上一步
          </el-button>
          <el-button type="primary" v-if="currentStep < 3" @click="nextStep">
            下一步
          </el-button>
          <el-button type="success" v-if="currentStep === 3" @click="saveTask">
            保存任务
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 添加账号弹窗 -->
    <el-dialog v-model="accountDialogVisible" title="添加账号" width="500px">
      <el-form :model="newAccount" label-width="100px">
        <el-form-item label="账号">
          <el-input v-model="newAccount.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newAccount.password" type="password" />
        </el-form-item>
        <el-form-item label="Cookie">
          <el-input v-model="newAccount.cookie" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="accountDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addAccount">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加代理弹窗 -->
    <el-dialog v-model="proxyDialogVisible" title="添加代理" width="500px">
      <el-form :model="newProxy" label-width="100px">
        <el-form-item label="代理地址">
          <el-input v-model="newProxy.host" />
        </el-form-item>
        <el-form-item label="端口">
          <el-input v-model="newProxy.port" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="newProxy.type">
            <el-option label="HTTP" value="http" />
            <el-option label="SOCKS5" value="socks5" />
          </el-select>
        </el-form-item>
        <el-form-item label="认证信息">
          <el-input v-model="newProxy.username" placeholder="用户名" />
          <el-input v-model="newProxy.password" type="password" placeholder="密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="proxyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addProxy">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 当前步骤
const currentStep = ref(0)

// 统计数据
const statistics = ref([
  { title: '总任务数', value: 125, icon: 'DataLine' },
  { title: '运行中任务', value: 8, icon: 'Loading' },
  { title: '今日数据量', value: '12,456', icon: 'DataAnalysis' },
  { title: '可用账号', value: 32, icon: 'User' }
])

// 平台配置
const platformConfig = reactive({
  platform: '',
  accounts: [],
  proxyType: 'none',
  proxyList: []
})

// 规则配置
const ruleConfig = reactive({
  dataTypes: [],
  dateRange: [],
  keywords: [],
  filters: [],
  advanced: {
    requestInterval: 1,
    timeout: 30,
    retryTimes: 3
  }
})

// 预览数据
const previewLoading = ref(false)
const previewData = ref([])
const previewColumns = ref([])
const previewStats = ref('')

// 任务配置
const taskConfig = reactive({
  name: '',
  executeType: 'once',
  scheduleTime: null,
  period: 'daily',
  periodicTime: null,
  dataProcessing: [],
  storageType: 'database',
  fileFormat: 'csv'
})

// 弹窗控制
const accountDialogVisible = ref(false)
const proxyDialogVisible = ref(false)

// 新账号/代理表单
const newAccount = reactive({
  username: '',
  password: '',
  cookie: ''
})

const newProxy = reactive({
  host: '',
  port: '',
  type: 'http',
  username: '',
  password: ''
})

// 可用数据类型
const availableDataTypes = [
  { label: '用户信息', value: 'userInfo' },
  { label: '发布内容', value: 'posts' },
  { label: '评论数据', value: 'comments' },
  { label: '互动数据', value: 'interactions' }
]

// 可用字段
const availableFields = [
  { label: '点赞数', value: 'likes' },
  { label: '评论数', value: 'comments' },
  { label: '转发数', value: 'shares' },
  { label: '播放量', value: 'views' }
]

const platformList = [
  { label: '抖音', value: 'douyin' },
  { label: '快手', value: 'kuaishou' },
  { label: '小红书', value: 'xiaohongshu' },
  { label: 'B站', value: 'bilibili' },
  { label: '微博', value: 'weibo' },
]

// 方法
const nextStep = () => {
  if (validateCurrentStep()) {
    currentStep.value++
  }
}

const prevStep = () => {
  currentStep.value--
}

const validateCurrentStep = () => {
  switch (currentStep.value) {
    case 0:
      if (!platformConfig.platform) {
        ElMessage.warning('请选择平台')
        return false
      }
      if (platformConfig.accounts.length === 0) {
        ElMessage.warning('请至少选择一个账号')
        return false
      }
      break
    case 1:
      if (ruleConfig.dataTypes.length === 0) {
        ElMessage.warning('请至少选择一种数据类型')
        return false
      }
      break
    // ... 其他步骤验证
  }
  return true
}

// 账号相关方法
const handleAccountSelection = (selection) => {
  platformConfig.accounts = selection
}

const showAddAccountDialog = () => {
  accountDialogVisible.value = true
}

const addAccount = async () => {
  try {
    // 调用API添加账号
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('账号添加成功')
    accountDialogVisible.value = false
  } catch (error) {
    ElMessage.error('账号添加失败')
  }
}

// 代理相关方法
const showAddProxyDialog = () => {
  proxyDialogVisible.value = true
}

const addProxy = async () => {
  try {
    // 调用API添加代理
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('代理添加成功')
    proxyDialogVisible.value = false
  } catch (error) {
    ElMessage.error('代理添加失败')
  }
}

// 预览相关方法
const fetchPreviewData = async () => {
  previewLoading.value = true
  try {
    // 调用API获取预览数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    previewData.value = [
      // 示例数据
    ]
    previewStats.value = '预计可抓取数据约1000条'
  } finally {
    previewLoading.value = false
  }
}

// 保存任务
const saveTask = async () => {
  try {
    // 调用API保存任务
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('任务保存成功')
    // 跳转到任务列表
  } catch (error) {
    ElMessage.error('任务保存失败')
  }
}
</script>

<style lang="scss" scoped>
.crawler-config {
  padding: 20px;

  .stat-cards {
    margin-bottom: 20px;

    .stat-card {
      display: flex;
      align-items: center;
      gap: 15px;

      .stat-icon {
        font-size: 24px;
        color: #409eff;
      }

      .stat-info {
        .stat-title {
          font-size: 14px;
          color: #666;
        }

        .stat-value {
          font-size: 20px;
          font-weight: bold;
          margin-top: 5px;
        }
      }
    }
  }

  .config-main {
    .step-content {
      margin-top: 30px;
      padding: 20px;
    }

    .platform-option {
      display: flex;
      align-items: center;
      gap: 10px;

      .platform-icon {
        width: 20px;
        height: 20px;
      }
    }

    .account-config,
    .proxy-list {
      margin-top: 10px;
    }

    .filter-item {
      display: flex;
      gap: 10px;
      margin-bottom: 10px;
    }

    .preview-actions {
      margin-bottom: 20px;
    }

    .preview-stats {
      margin-top: 20px;
    }

    .step-actions {
      margin-top: 30px;
      display: flex;
      justify-content: center;
      gap: 20px;
    }
  }
}
</style>